<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

// 应用公共文件


if(!function_exists('genRandomNum')) {
    /**
     * 获取随机数
     * @date   2016-01-11
     * @author Lanlc
     *
     * @param  int  $len  随机数长度
     *
     * @return
     */
    function genRandomNum($len)
    {
        $chars = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 0);
        $charsLen = count($chars) - 1;
        shuffle($chars);    // 将数组打乱
        $output = "";
        for ($i = 0; $i < $len; $i++) {
            $output .= $chars[mt_rand(0, $charsLen)];
        }
        return $output;
    }
}

if (!function_exists('getThousandString')) {
    function getThousandString ($num) {
        $len = strlen($num);
        switch ($len) {
            case 1:
                $num = '000'.$num;
                break;
            case 2:
                $num = '00'.$num;
                break;
            case 3:
                $num = '0'.$num;
                break;
            default:
                break;
        }
        return $num;
    }
}

if (!function_exists('getMillionString')) {
    function getMillionString ($num) {
        $len = strlen($num);
        switch ($len) {
            case 1:
                $num = '000000'.$num;
                break;
            case 2:
                $num = '00000'.$num;
                break;
            case 3:
                $num = '0000'.$num;
                break;
            case 4:
                $num = '000'.$num;
                break;
            case 5:
                $num = '00'.$num;
                break;
            case 6:
                $num = '0'.$num;
                break;
            default:
                break;
        }
        return $num;
    }
}
if(!function_exists('genRandomString')) {
    /**
     * 获取随机码
     * @date   2016-01-11
     * @author Lanlc
     *
     * @param  int $len 随机数长度
     *
     * @return
     */
    function genRandomString($len) {
        $srcstr="ABCDEFGHIJKLMNPQRSTUVWXYZ123456789";
        mt_srand();
        $strs="";
        for($i=0;$i<$len;$i++) {
            $strs.=$srcstr[mt_rand(0,33)];
        }
        return ($strs);
    }
}

if (!function_exists('curl_post')) {
    /**
     * CURL 提交请求数据
     *
     * @author lanlc
     * @date   2016-04-11
     * @param string $url 请求URL
     * @param string $postData 请求发送的数据
     * @param int $port 请求端口
     * @param int $timeout 超时时间
     * @param string $logPath 错误日志文件
     * @param array $http_headers 请求头信息
     * @param bool $ret_errcode 是否返回curl错误码
     * @param array [user,pwd]  CURLOPT_USERPWD 的设置参数
     * @return bool|mixed
     */
    function curl_post($url, $postData, $port = 80, $timeout = 25, $logPath = '/api/curl_post', $http_headers = [], $ret_errcode = false, $userpwd = '') {
        $ch       = curl_init();
        $url_info = parse_url($url);
        $port     = isset($url_info['port']) ? $url_info['port'] : $port;
        //$basePath = strpos($logPath, BASE_LOG_DIR)!==false ?  '' : BASE_LOG_DIR;
        $logPath = str_replace(BASE_LOG_DIR, '', $logPath);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_PORT, $port);
        curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        if ((is_array($http_headers) || is_object($http_headers)) && count($http_headers)) {
            curl_setopt($ch, CURLOPT_HTTPHEADER, $http_headers);
        }
        if ($userpwd != '' && is_array($userpwd)) {
            curl_setopt($ch, CURLOPT_USERPWD, "{$userpwd[0]}:{$userpwd[1]}");
        }
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        $res = curl_exec($ch);
        //错误处理
        $errCode = curl_errno($ch);
        if ($errCode > 0) {
            //记录日志
            $logData = json_encode(array(
                'url'       => $url,
                'err_code'  => $errCode,
                'err_msg'   => curl_error($ch),
                'post_data' => $postData,
            ));
            zft_log($logPath, $logData);
            curl_close($ch);
            if ($ret_errcode === true) {
                return array('status' => false, 'code' => $errCode);
            }

            //返回false
            return false;
        } else {
            //获取HTTP码
            $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            if ($httpCode != 200) {
                //接口错误
                $logData = json_encode(array(
                    'url'       => $url,
                    'err_code'  => $httpCode,
                    'err_msg'   => $res,
                    'post_data' => $postData,
                ));
                zft_log($logPath, $logData);
                curl_close($ch);
                if ($ret_errcode === true) {
                    return array('status' => false, 'code' => $httpCode);
                }

                return false;
            } else {
                curl_close($ch);
                return $res;
            }
        }
    }
}


/**
 * This function adds once the CKEditor's config vars
 * @author Samuel Sanchez
 * @access private
 * @param array $data (default: array())
 * @return string
 */
function cke_initialize($data = array()) {

	$return = '';

	if(!defined('CI_CKEDITOR_HELPER_LOADED')) {
		if (!isset($data['path'])) $data['path'] = '/static/editor/ckeditor/';
		define('CI_CKEDITOR_HELPER_LOADED', TRUE);
		$return =  '<script type="text/javascript" src="'.$data['path'] . 'ckeditor.js"></script>';
		$return .=  '<script type="text/javascript" src="/static/editor/ckfinder/ckfinder.js"></script>';
		$return .=	"<script type=\"text/javascript\">CKEDITOR_BASEPATH = '" . $data['path'] . "';</script>";
	}

	return $return;

}

/**
 * This function create JavaScript instances of CKEditor
 * @author Samuel Sanchez
 * @access private
 * @param array $data (default: array())
 * @return string
 */
function cke_create_instance($data = array()) {

    $return = "<script type=\"text/javascript\">
     	var editor = CKEDITOR.replace('" . $data['id'] . "', {";

    		if(!isset($data['config']['width'])) $data['config']['width'] = '600';
			if(!isset($data['config']['height'])) $data['config']['height'] = '600';

    		//Adding config values
    		if(isset($data['config'])) {


	    		foreach($data['config'] as $k=>$v) {

	    			// Support for extra config parameters
	    			if (is_array($v)) {
	    				$return .= $k . " : [";
	    				$return .= config_data($v);
	    				$return .= "]";

	    			}
	    			else {
	    				$return .= $k . " : '" . $v . "'";
	    			}

	    			if(array_key_exists($k,$data['config'])) {
						$return .= ",";
					}
	    		}
    		}

    $return .= '}); CKFinder.setupCKEditor( editor, "__PUBLIC__/editor/ckfinder/" );</script>';

    return $return;

}

/**
 * This function displays an instance of CKEditor inside a view
 * @author Samuel Sanchez
 * @access public
 * @param array $data (default: array())
 * @return string
 */
function display_ckeditor($data = array())
{
	// Initialization
	$return = cke_initialize($data);

    // Creating a Ckeditor instance
    $return .= cke_create_instance($data);


    // Adding styles values
    if(isset($data['styles'])) {

    	$return .= "<script type=\"text/javascript\">CKEDITOR.addStylesSet( 'my_styles_" . $data['id'] . "', [";


	    foreach($data['styles'] as $k=>$v) {

	    	$return .= "{ name : '" . $k . "', element : '" . $v['element'] . "', styles : { ";

	    	if(isset($v['styles'])) {
	    		foreach($v['styles'] as $k2=>$v2) {

	    			$return .= "'" . $k2 . "' : '" . $v2 . "'";

					if($k2 !== end(array_keys($v['styles']))) {
						 $return .= ",";
					}
	    		}
    		}

	    	$return .= '} }';

	    	if($k !== end(array_keys($data['styles']))) {
				$return .= ',';
			}


	    }

	    $return .= ']);';

		$return .= "CKEDITOR.instances['" . $data['id'] . "'].config.stylesCombo_stylesSet = 'my_styles_" . $data['id'] . "';
		</script>";
    }

    return $return;
}

/**
 * config_data function.
 * This function look for extra config data
 *
 * @author ronan
 * @link http://kromack.com/developpement-php/codeigniter/ckeditor-helper-for-codeigniter/comment-page-5/#comment-545
 * @access public
 * @param array $data. (default: array())
 * @return String
 */
function config_data($data = array())
{
	$return = '';
	foreach ($data as $k => $key)
	{
		if (is_array($key)) {
			$return .= "[";
			foreach ($key as $k2 => $string) {
				$return .= "'" . $string . "'";
				if(array_key_exists($k2,$key)) $return .= ",";
			}
			$return .= "]";
		}
		else {
			$return .= "'".$key."'";
		}
		if(array_key_exists($k,$key)) $return .= ",";

	}
	return $return;
}

/**
 * 获取输入参数 支持过滤和默认值
 * 使用方法:
 * <code>
 * I('id',0); 获取id参数 自动判断get或者post
 * I('post.name','','htmlspecialchars'); 获取$_POST['name']
 * I('get.'); 获取$_GET
 * </code>
 * @param string $name 变量的名称 支持指定类型
 * @param mixed $default 不存在的时候默认值
 * @param mixed $filter 参数过滤方法
 * @param mixed $datas 要获取的额外数据源
 * @return mixed
 */
function I($name, $default = '', $filter = null, $datas = null)
{
    static $_PUT = null;
    if (strpos($name, '/')) {
        // 指定修饰符
        list($name, $type) = explode('/', $name, 2);
    } elseif (C('VAR_AUTO_STRING')) {
        // 默认强制转换为字符串
        $type = 's';
    }
    if (strpos($name, '.')) {
        // 指定参数来源
        list($method, $name) = explode('.', $name, 2);
    } else {
        // 默认为自动判断
        $method = 'param';
    }
    switch (strtolower($method)) {
        case 'get':
            $input = &$_GET;
            break;
        case 'post':
            $input = &$_POST;
            break;
        case 'put':
            if (is_null($_PUT)) {
                parse_str(file_get_contents('php://input'), $_PUT);
            }
            $input = $_PUT;
            break;
        case 'param':
            switch ($_SERVER['REQUEST_METHOD']) {
                case 'POST':
                    $input = $_POST;
                    break;
                case 'PUT':
                    if (is_null($_PUT)) {
                        parse_str(file_get_contents('php://input'), $_PUT);
                    }
                    $input = $_PUT;
                    break;
                default:
                    $input = $_GET;
            }
            break;
        case 'path':
            $input = array();
            if (!empty($_SERVER['PATH_INFO'])) {
                $depr  = C('URL_PATHINFO_DEPR');
                $input = explode($depr, trim($_SERVER['PATH_INFO'], $depr));
            }
            break;
        case 'request':
            $input = &$_REQUEST;
            break;
        case 'session':
            $input = &$_SESSION;
            break;
        case 'cookie':
            $input = &$_COOKIE;
            break;
        case 'server':
            $input = &$_SERVER;
            break;
        case 'globals':
            $input = &$GLOBALS;
            break;
        case 'data':
            $input = &$datas;
            break;
        default:
            return null;
    }
    if ('' == $name) {
        // 获取全部变量
        $data    = $input;
        $data = safeSql($data);
        $filters = isset($filter) ? $filter : C('DEFAULT_FILTER');
        if ($filters) {
            if (is_string($filters)) {
                $filters = explode(',', $filters);
            }
            foreach ($filters as $filter) {
                $data = array_map_recursive($filter, $data); // 参数过滤
            }
        }
    } elseif (isset($input[$name])) {
        // 取值操作
        $data    = $input[$name];
        $data = safeSql($data);
        $filters = isset($filter) ? $filter : C('DEFAULT_FILTER');
        if ($filters) {
            if (is_string($filters)) {
                if (0 === strpos($filters, '/')) {
                    if (1 !== preg_match($filters, (string) $data)) {
                        // 支持正则验证
                        return isset($default) ? $default : null;
                    }
                } else {
                    $filters = explode(',', $filters);
                }
            } elseif (is_int($filters)) {
                $filters = array($filters);
            }

            if (is_array($filters)) {
                foreach ($filters as $filter) {
                    $filter = trim($filter);
                    if (function_exists($filter)) {
                        $data = is_array($data) ? array_map_recursive($filter, $data) : $filter($data); // 参数过滤
                    } else {
                        $data = filter_var($data, is_int($filter) ? $filter : filter_id($filter));
                        if (false === $data) {
                            return isset($default) ? $default : null;
                        }
                    }
                }
            }
        }

        if (!empty($type)) {
            switch (strtolower($type)) {
                case 'a': // 数组
                    $data = (array) $data;
                    break;
                case 'd': // 数字
                    $data = (int) $data;
                    break;
                case 'f': // 浮点
                    $data = (float) $data;
                    break;
                case 'b': // 布尔
                    $data = (boolean) $data;
                    break;
                case 's': // 字符串
                default:
                    $data = (string) $data;
            }
        }
    } else {
        // 变量默认值
        $data = isset($default) ? $default : null;
    }
    is_array($data) && array_walk_recursive($data, 'think_filter');
    return $data;
}

function array_map_recursive($filter, $data) {
    $result = array();
    foreach ($data as $key => $val) {
        $result[$key] = is_array($val)
            ? array_map_recursive($filter, $val)
            : call_user_func($filter, $val);
    }
    return $result;
}

if (!function_exists('C')) {
    /**
     * 获取和设置配置参数 支持批量定义
     * @param string|array $name 配置变量
     * @param mixed $value 配置值
     * @param mixed $default 默认值
     * @return mixed
     */
    function C($name = null, $value = null, $default = null){
        static $_config = array();
        // 无参数时获取所有
        if (empty($name)) {
            return $_config;
        }
        // 优先执行设置获取或赋值
        if (is_string($name)) {
            if (!strpos($name, '.')) {
                $name = strtoupper($name);
                if (is_null($value)) {
                    return isset($_config[$name]) ? $_config[$name] : $default;
                }

                $_config[$name] = $value;
                return null;
            }
            // 二维数组设置和获取支持
            $name    = explode('.', $name);
            $name[0] = strtoupper($name[0]);
            if (is_null($value)) {
                return isset($_config[$name[0]][$name[1]]) ? $_config[$name[0]][$name[1]] : $default;
            }

            $_config[$name[0]][$name[1]] = $value;
            return null;
        }
        // 批量设置
        if (is_array($name)) {
            $_config = array_merge($_config, array_change_key_case($name, CASE_UPPER));
            return null;
        }
        return null; // 避免非法参数
    }
}

if(!function_exists('zft_log')) {
    function zft_log($path, $content, $mode = 'day') {
        $path = strval($path);
        $path = str_replace('\\', '/', trim($path, '/'));

        $content = strval($content);

        if (!$path || !$content) {
            return false;
        }
        $mode = in_array($mode, array('day', 'month', 'year')) ? $mode : 'day';
        $tempPath = BASE_LOG_DIR . '/' . $path . '/';

        if ($mode == 'day') {
            $tempPath .= date('Y') . '/' . date('m') . '/';
            $fileName  = date('d'). '.log';
        } elseif ($mode == 'month') {
            $tempPath .= date('Y') . '/';
            $fileName  = date('m'). '.log';
        } else {
            $fileName = date('Y') . 'log';
        }

        if (!file_exists($tempPath)) {
            if (!mkdir($tempPath, 0777, true)) {
                return false;
            }
        }

        $file    = $tempPath . $fileName;
        $content = date('Y-m-d H:i:s') . '#' . $content . "\r\n";
        $res     = @file_put_contents($file, $content, FILE_APPEND);
        if ($res) {
            return true;
        } else {
            return false;
        }
    }
}

if (!function_exists('ismobile')) {
    function ismobile($tel) {
        if(!preg_match('/^(14|15|13|18|17)\d{9}$/',$tel)){
            return false;
        }
        return true;
    }
}

// 18位身份证校验码有效性检查
if (!function_exists('isIDCard')) {
    function isIDCard($idcard){
        if(strlen($idcard)!=18) return false;
        $idcard_base = substr($idcard, 0, 17);
        return (idcard_verify_number($idcard_base)!=strtoupper(substr($idcard,17,1))) ? false:true;
    }
}


// 计算身份证校验码，根据国家标准GB 11643-1999
if (!function_exists('idcard_verify_number')) {
    function idcard_verify_number($idcard_base){
        if(strlen($idcard_base)!=17) return false;
        //加权因子
        $factor = array(7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2);

        //效验码对应值
        $verify_number_list = array('1','0','X','9','8','7','6','5','4','3','2');
        $checksum = 0;
        for($i=0;$i<strlen($idcard_base);$i++){
            $checksum += substr($idcard_base,$i,1) * $factor[$i];
        }

        $mod = $checksum % 11;
        $verify_number = $verify_number_list[$mod];
        return $verify_number;
    }
}

if (!function_exists('getRatio')) {
    function getRatio($ratio) {
        $ratio = substr($ratio, 0, 5);
        if (strpos($ratio, '：')) {
            $ratio = str_replace('：', ":", $ratio);
        }
        return $ratio;
    }
}

if (!function_exists('handleDay')) {
    function handleDay($day) {
        if (!$day) {
            return false;
        }
        if (intval($day) < 10) {
            return '0'.$day;
        }
        return $day;
    }
}


if (!function_exists('fen')) {
    function fen($param) {
        if (is_numeric($param)) {
            return round($param*100);
        } else {
            return 0;
        }
    }
}

if (!function_exists('yuan')) {
    function yuan($param) {
        if (is_numeric($param)) {
            return round($param/100, 2);
        } else {
            return 0;
        }

    }
}

if (!function_exists('alert')) {
    function alert($msg, $url='close') {
        echo '<script type="text/javascript">';
        echo 'alert("'.$msg.'");';
        if ($url != 'close') {
            if ($url)
                echo 'window.location.href="'. $url.'";';
        } else {
            echo 'window.close();';
        }
        echo '</script>';
        die;
    }
}
if (!function_exists('safeSql')) {
    function safeSql($str) {
        if ($str == '' && $str !== 0) {
            return false;
        }
        if (is_array($str)) {
            foreach ($str as $key => $val) {
                $str[$key] = safeSql($val);
            }
            return $str;
        } else {
            $str = str_replace("and","",$str);
            $str = str_replace("AND","",$str);
            $str = str_replace("execute","",$str);
            $str = str_replace("EXECUTE","",$str);
            $str = str_replace("update","",$str);
            $str = str_replace("UPDATE","",$str);
            $str = str_replace("count","",$str);
            $str = str_replace("COUNT","",$str);
            $str = str_replace("chr","",$str);
            $str = str_replace("CHR","",$str);
            $str = str_replace("mid","",$str);
            $str = str_replace("MID","",$str);
            $str = str_replace("master","",$str);
            $str = str_replace("MASTER","",$str);
            $str = str_replace("truncate","",$str);
            $str = str_replace("TRUNCATE","",$str);
            $str = str_replace("char","",$str);
            $str = str_replace("CHAR","",$str);
            $str = str_replace("declare","",$str);
            $str = str_replace("DECLARE","",$str);
            $str = str_replace("select","",$str);
            $str = str_replace("SELECT","",$str);
            $str = str_replace("create","",$str);
            $str = str_replace("CREATE","",$str);
            $str = str_replace("delete","",$str);
            $str = str_replace("DELETE","",$str);
            $str = str_replace("insert","",$str);
            $str = str_replace("INSERT","",$str);
            $str = str_replace("union","",$str);
            $str = str_replace("UNION","",$str);
            $str = str_replace("contact","",$str);
            $str = str_replace("CONTACT","",$str);
            $str = str_replace("replace","",$str);
            $str = str_replace("REPLACE","",$str);
            $str = str_replace("'","",$str);
            $str = str_replace(" ","",$str);
            $str = str_replace("or","",$str);
            $str = str_replace("=","",$str);
            $str = str_replace("%20","",$str);
            $str = str_replace("%","",$str);
            return $str;
        }
    }
}
//读取配置文件
if (!function_exists('load_config')) {
    /**
     * 动态加载业务配置数据
     * @param string $key 配置的键
     * @param string $type 配置文件类型，默认auth权限设置
     * @return mixed
     */
    function load_config($key, $type = 'auth') {
        static $_load_config = array();

        $key  = strval($key);
        $type = strval($type);

        // 无参数时获取所有
        if ($key == '' || empty($type)) {
            return null;
        }

        //获取配置文件的所有配置
        if (isset($_load_config[$type])) {
            $configArr = $_load_config[$type];
        } else {
            $configFile = HTML_DIR . "/application/Conf/{$type}.conf.php";
            if (file_exists($configFile)) {
                $configArr = include $configFile;
            } else {
                $configArr = array();
            }

            $_load_config[$type] = $configArr;
        }

        if (isset($configArr[$key])) {
            return $configArr[$key];
        } else {
            return null;
        }
    }
}
//读取excel文件
if (!function_exists('load_excel')) {
    function load_excel() {
        static $PHPExcel;
        if (!empty($PHPExcel) && is_object($PHPExcel)) {
            return $PHPExcel;
        }
        $file = HTML_DIR . '/extend/Business/PHPExcel.php';
        include_once $file;
        $PHPExcel = new PHPExcel();
        return $PHPExcel;
    }
}
//获取运行时间
if (!function_exists('microtime_float')) {
    function microtime_float() {
        list($usec, $sec) = explode(" ", microtime());
        return ((float)$usec + (float)$sec);
    }
}

//计算两个日期相隔多少年,月,天 格式2017-04-11
if (!function_exists('diffDate')) {
    function diffDate($date1,$date2){
        if (!strtotime($date1) || !strtotime($date2))
            return false;
        if(strtotime($date1)>strtotime($date2)){
            $tmp=$date2;
            $date2=$date1;
            $date1=$tmp;
        }
        list($Y1,$m1,$d1)=explode('-',$date1);
        list($Y2,$m2,$d2)=explode('-',$date2);
        $Y=$Y2-$Y1;
        $m=$m2-$m1;
        $d=$d2-$d1;
        if($d<0){
            $d+=(int)date('t',strtotime("-1 month $date2"));
            $m--;
        }
        if($m<0){
            $m+=12;
            $Y--;
        }
        return array('year'=>$Y,'month'=>$m,'day'=>$d);
    }
}

//var_dump调试
if (!function_exists('dd')) {
    function dd() {
        $array = func_get_args();
        foreach ($array as $value) {
            var_dump($value);
        }
        die;
    }
}

//根据输入的金额类型,返回金额类型中文名
if (!function_exists('getMoneyType')) {
    function getMoneyType($type) {
        $typeMoney = '';
        switch ($type) {
            case 9 :
                $typeMoney = '优惠金额';
                break;
            case 1 :
                $typeMoney = '房租';
                break;
            case 2 :
                $typeMoney = '物业费';
                break;
            case 3 :
                $typeMoney = '水费';
                break;
            case 4 :
                $typeMoney = '电费';
                break;
            case 5 :
                $typeMoney = '公摊水费';
                break;
            case 6 :
                $typeMoney = '公摊电费';
                break;
            case 7 :
                $typeMoney = '税费';
                break;
            case 8 :
                $typeMoney = '其他费用';
                break;
            default:
                $typeMoney = '';
                break;
        }
        return $typeMoney;
    }
}

//检查费用类型是否合法
if (!function_exists('checkMoneyType')) {
    function checkMoneyType($type) {
        if (in_array($type, [9,1,2,3,4,5,6,7,8])) {
            return true;
        } else {
            return false;
        }
    }
}

/**
 * 获取客户端IP地址
 * @param integer $type 返回类型 0 返回IP地址 1 返回IPV4地址数字
 * @param boolean $adv 是否进行高级模式获取（有可能被伪装）
 * @return mixed
 */
if (!function_exists('get_client_ip')) {
    function get_client_ip($type = 0, $adv = false) {
        $type = $type ? 1 : 0;
        static $ip = null;
        if (null !== $ip) {
            return $ip[$type];
        }

        if ($adv) {
            if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
                $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
                $pos = array_search('unknown', $arr);
                if (false !== $pos) {
                    unset($arr[$pos]);
                }

                $ip = trim($arr[0]);
            } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
                $ip = $_SERVER['HTTP_CLIENT_IP'];
            } elseif (isset($_SERVER['REMOTE_ADDR'])) {
                $ip = $_SERVER['REMOTE_ADDR'];
            }
        } elseif (isset($_SERVER['REMOTE_ADDR'])) {
            $ip = $_SERVER['REMOTE_ADDR'];
        }
        // IP地址合法验证
        $long = sprintf("%u", ip2long($ip));
        $ip   = $long ? [$ip, $long] : ['0.0.0.0', 0];
        return $ip[$type];
    }
}

/**
 * 检验登录密码
 * @param  string  $p1        新密码
 *
 * @return mixed
 */
if (!function_exists('chkPassWord1')) {
    function chkPassword1($p1)
    {
        if (!$p1) {
            return false;
        }
        $p1 = strval($p1);
        $commonWeakPassword = array (
            '123456','a123456','a123456789','woaini1314','qq123456','abc123456',
            '123456a','123456789a','abc123','qq123456789','123456789.',
            'woaini','q123456','123456abc','123456.','0123456789',
            'asd123456','aa123456','q123456789','abcd123456','woaini520',
            'woaini123','w123456','aini1314','abc123456789','woaini521',
            'qwertyuiop','qwe123456','asd123','123456789abc','z123456',
            'aaa123456','abcd1234','www123456','123456789q','123abc',
            'qwe123','w123456789','123456qq','zxc123456','qazwsxedc',
            '123456..','zxc123','asdfghjkl','123456q','123456aa',
            '9876543210','qaz123456','qq5201314','as123456',
            'z123456789','a123123','a5201314','wang123456','abcd123',
            '123456789..','woaini1314520','123456asd','aa123456789',
            '741852963','a12345678',
        );

        $len = mb_strlen($p1, 'utf-8');
        if ($len < 6 || $len > 20) {
            return "密码长度必须大于6小于20" . $len;
        } elseif (ctype_digit($p1) || ctype_alpha($p1)) {
            //纯数字&纯字母的提示
            return '您设置的密码过于简单，请输入6-20位数字、字母或常用符号，字母区分大小写';
        } elseif (in_array($p1, $commonWeakPassword)) {
            return '您输入的密码太常见，很容易被人猜出，请重新选择无规则的数字字母组合。';
        } elseif (preg_match('/\s/', $p1)) {
            return "密码仅支持英文、数字和字符，不支持空格";
        }
        return true;
    }
}

/**
 * 检验登录密码
 * @param  string  $p1        新密码
 * @param  string  $p2        再次输入
 *
 * @return mixed
 */
if (!function_exists('chkPassWord')) {
    function chkPassword($p1, $p2)
    {
        if (!$p1 || !$p2) {
            return false;
        }
        $p1 = strval($p1);
        $commonWeakPassword = array (
            '123456','a123456','a123456789','woaini1314','qq123456','abc123456',
            '123456a','123456789a','abc123','qq123456789','123456789.',
            'woaini','q123456','123456abc','123456.','0123456789',
            'asd123456','aa123456','q123456789','abcd123456','woaini520',
            'woaini123','w123456','aini1314','abc123456789','woaini521',
            'qwertyuiop','qwe123456','asd123','123456789abc','z123456',
            'aaa123456','abcd1234','www123456','123456789q','123abc',
            'qwe123','w123456789','123456qq','zxc123456','qazwsxedc',
            '123456..','zxc123','asdfghjkl','123456q','123456aa',
            '9876543210','qaz123456','qq5201314','as123456',
            'z123456789','a123123','a5201314','wang123456','abcd123',
            '123456789..','woaini1314520','123456asd','aa123456789',
            '741852963','a12345678',
        );

        $len = mb_strlen($p1, 'utf-8');
        if ($p1 != $p2) {
            return "两次密码输入不一致";
        } elseif ($len < 6 || $len > 20) {
            return "密码长度必须大于6小于20,您输入了" . $len.'位';
        } elseif (ctype_digit($p1) || ctype_alpha($p1)) {
            //纯数字&纯字母的提示
            return '您设置的密码过于简单，请输入6-20位数字、字母或常用符号，字母区分大小写';
        } elseif (in_array($p1, $commonWeakPassword)) {
            return '您输入的密码太常见，很容易被人猜出，请重新选择无规则的数字字母组合。';
        } elseif (preg_match('/\s/', $p1)) {
            return "密码仅支持英文、数字和字符，不支持空格";
        }
        return true;
    }
}

/**
 * 检验提现密码
 * @param  string  $p1        新密码
 * @param  string  $p2        再次输入
 *
 * @return mixed
 */
if (!function_exists('chkWithdrawPwd')) {
    function chkWithdrawPwd($p1, $p2)
    {
        if (!$p1 || !$p2) {
            return false;
        }
        $p1 = strval($p1);

        $len = mb_strlen($p1, 'utf-8');
        if ($p1 != $p2) {
            return "两次密码输入不一致";
        } elseif ($len != 6) {
            return "密码长度必须位6位,您输入了" . $len.'位';
        } elseif (!ctype_digit($p1)) {
            //纯数字&纯字母的提示
            return '您设置的密码存在非数字字符，请重新设置';
        } elseif (preg_match('/\s/', $p1)) {
            return "密码不支持空格";
        }
        return true;
    }
}

/**
 * 获取到毫秒
 * @return float
 */
if (!function_exists('getMillisecond')) {
    function getMillisecond()
    {
        list($t1, $t2) = explode(' ', microtime());
        return (float)sprintf('%.0f', (floatval($t1) + floatval($t2)) * 1000);
    }
}

/**
 * 创建目录
 * @return float
 */
if (!function_exists('createDir')) {
    function createDir($pathStr)
    {
        if ( !file_exists( $pathStr ) ) {
            if ( !mkdir( $pathStr , 0777 , true ) ) {
                return false;
            }
        }
    }
}

/**
 * 删除目录及目录下所有文件或删除指定文件
 * @param str $path   待删除目录路径
 * @param int $delDir 是否删除目录，1或true删除目录，0或false则只删除文件保留目录（包含子目录）
 * @return bool 返回删除状态
 */
if (!function_exists('delDirAndFile')) {
    function delDirAndFile($path, $delDir = FALSE)
    {
        if (!file_exists($path)) {
            return FALSE;
        }
        $handle = opendir($path);
        if ($handle) {
            while (false !== ($item = readdir($handle))) {
                if ($item != "." && $item != "..")
                    is_dir("$path/$item") ? delDirAndFile("$path/$item", $delDir) : unlink("$path/$item");
            }
            closedir($handle);
            if ($delDir)
                return rmdir($path);
        } else {
            if (file_exists($path)) {
                return unlink($path);
            } else {
                return FALSE;
            }
        }
    }
}






